//
// Created by Chen qin lang on 2018/7/6.
//

#include "JavaCall.h"
#include "WlFFmpeg.h"

JavaCall::JavaCall(_JavaVM *javaVM, JNIEnv *jniEnv, jobject instance) : javaVM(javaVM), jniEnv(jniEnv)
{

    this->instance = jniEnv->NewGlobalRef(instance);//需要重新构建instance 当方法执行完弹栈为空 5.0之后jni挥挥手 jobeject 需要newglobalref
    jclass pJclass = jniEnv->GetObjectClass(instance);
    if (!pJclass){
        LOGE("not found jobject");
        return ;
    }
     id = jniEnv->GetMethodID(pJclass, "prepared", "(I)V");
    errorId = jniEnv->GetMethodID(pJclass, "error", "()V");
    callLoadid = jniEnv->GetMethodID(pJclass, "onCallLoad", "(Z)V");
    callTimeinfo=jniEnv->GetMethodID(pJclass,"onCallTimeInfo","(II)V");
    callComplete=jniEnv->GetMethodID(pJclass,"onCallComplete","()V");
}

void JavaCall::onPrepared(int type) {
    JNIEnv *env;
    if (type == MAIN_THREAD) {
        jniEnv->CallVoidMethod(instance, id,type);
    } else if (type == CHILD_THREAD) {
        if (javaVM->AttachCurrentThread(&env, 0) == JNI_OK) {
            LOGE("jobject %p jid :%p",instance,id);
            env->CallVoidMethod(instance, id,type);
            javaVM->DetachCurrentThread();
        }
    }

}

void JavaCall::onError(int type) {
    JNIEnv *env;
    if (type == MAIN_THREAD) {
        jniEnv->CallVoidMethod(instance, id);
    } else if (type == CHILD_THREAD) {
        if (javaVM->AttachCurrentThread(&env, 0) == JNI_OK) {
            env->CallVoidMethod(instance, id);
            javaVM->DetachCurrentThread();
        }
    }
}

void JavaCall::onCallLoad(int type, bool isload) {
    JNIEnv *env;
    if (type == MAIN_THREAD) {
        jniEnv->CallVoidMethod(instance, callLoadid,isload);
    } else if (type == CHILD_THREAD) {
        if (javaVM->AttachCurrentThread(&env, 0) == JNI_OK) {
            env->CallVoidMethod(instance, callLoadid,isload);
            javaVM->DetachCurrentThread();
        }
    }


}

void JavaCall::callTimeInfo(int type, int currentTime, int tatolTime) {


    if (type == MAIN_THREAD) {
        jniEnv->CallVoidMethod(instance, callTimeinfo,currentTime,tatolTime);
    } else if (type == CHILD_THREAD) {
        JNIEnv *env;
        if (javaVM->AttachCurrentThread(&env, 0) == JNI_OK) {
            env->CallVoidMethod(instance, callTimeinfo,currentTime,tatolTime);
            javaVM->DetachCurrentThread();
        }
    }
}
void JavaCall::onCallComplete(int type) {
    if (type == MAIN_THREAD) {
        jniEnv->CallVoidMethod(instance, callComplete);
    } else if (type == CHILD_THREAD) {
        JNIEnv *env;
        if (javaVM->AttachCurrentThread(&env, 0) == JNI_OK) {
            env->CallVoidMethod(instance, callComplete);
            javaVM->DetachCurrentThread();
        }
    }
}
JavaCall::~JavaCall() {
    LOGE("~JavaCall");

}


